import Vue from 'vue'
import { getAccessToken, getSerialNo, getTenantId } from '@/utils/auth'
import { config } from '@/config/config'
import axios from 'axios'
import { isHaveNetwork } from '@/utils'

const handleErrorWhiteList = [
  '/app-api/exam/app/module-use-time/create',
  '/app-api/exam/app/module-use-time/createBatch',
  '/app-api/question/databaseApp/startRead'
]

const service = axios.create({
  baseURL: config.baseUrl,
  withCredentials: false // 禁用 Cookie 等信息
})
service.interceptors.request.use(
  (config) => {
    config.headers['If-Modified-Since'] = '0'
    config.headers['Cache-Control'] = 'no-cache'

    if (config.method === 'get') {
      // 若是是get请求，且params是数组类型如arr=[1,2]，则转换成arr=1&arr=2
      config.paramsSerializer = function(params) {
        return qs.stringify(params, { arrayFormat: 'repeat' })
      }
    }
    return config
  },
  (error) => {
    console.log('requestError', error)
    return Promise.reject(error)
  }
)
service.interceptors.response.use(
  (res) => {
    return res
  },
  (error) => {
    // http断网错误和post缓存未命中错误
    if (error['code'] === 'ERR_NETWORK' || error['code'] === "ERR_BAD_RESPONSE") {
      // 如果存在加载动画，隐藏
      document.querySelectorAll('.el-loading-mask').forEach((loading) => {
        loading.hidden = true
      })

      if (isHaveNetwork()) {
        const msg = error['message']
        Vue.prototype.$message.error(`${msg}`)
      } else {
        const url = error.config.url

        if (handleErrorWhiteList.every((item) => url.indexOf(item) === -1)) {
          const isShowMessage = true
          document.querySelectorAll('.el-message--error').forEach(() => {
            isShowMessage = false
          })
          if (isShowMessage) {
            Vue.prototype.$message.error('请检查网络连接')
          }
        }
      }
    }
    console.log('responseError', error)
    return Promise.reject(error)
  }
)
export default function request(api, method, data, params) {
  return new Promise(async (reslove, reject) => {
    const res = await service({
      url: config.baseUrl + api,
      method: method || 'POST',
      headers: params.header || {
        'content-type': 'application/json',
        Authorization: await getAccessToken(),
        serialNo: await getSerialNo(),
        'tenant-id': await getTenantId()
      },
      dataType: 'json',
      data: data || {},
      params: method === 'get' ? data : {}
    })

    const { code, msg } = res.data

    if (code === 401) {
      const { android_call } = window
      if (android_call && isHaveNetwork()) {
        android.toLogin()
      } else {
        location.href = `${location.pathname}#/pages/login/index`
      }
    }

    if (msg === '系统异常') {
      // 如果存在加载动画，隐藏
      document.querySelectorAll('.el-loading-mask').forEach((loading) => {
        loading.hidden = true
      })

      Vue.prototype.$message.error(`${api} code: ${code} msg: ${msg}`)
      reject(msg)
      return
    }

    reslove(res.data)
  })
}

;
['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
  request[method] = (api, data, opt) => request(api, method, data, opt || {})
})
